<template>
  <div class="background">
    <div id="game-container" v-if="gameActive">
      <div class="status-bar">
        <div class="timer">时间: {{ formatTime(elapsedTime) }}</div>
        <div class="controls">
          <span>逃生者: WASD</span>
          <span>追击者: 方向键</span>
        </div>
        <div class="escape-time" v-if="escapeTimeLeft > 0">
          逃生剩余: {{ escapeTimeLeft }}秒
        </div>
        <div class="bush-warning" v-if="bushWarning">{{ bushWarning }}</div>
      </div>
      
      <!-- 逃生者（带消散动画） -->
      <div class="player escape" 
           :style="escapeStyle" 
           :class="{ 
             'hidden': isEscapeInBush,
             'disappearing': isDisappearing
           }">
        <div class="dissolve-effect" v-if="isDisappearing"></div>
      </div>
      
      <!-- 追击者 -->
      <div class="player chaser" 
           :style="chaserStyle" 
           :class="{ 'hidden': isChaserInBush }"></div>
      
      <!-- 逃生区域 -->
      <div class="escape-zone" 
           v-if="showEscapeZone" 
           :style="escapeZoneStyle"></div>
      
      <!-- 游戏元素 -->
      <div class="bush" 
           v-for="bush in activeBushes" 
           :key="`bush-${bush.x}-${bush.y}`" 
           :style="bushStyle(bush)">
      </div>
      
      <div class="obstacle"
           v-for="obstacle in obstacles"
           :key="`obstacle-${obstacle.x}-${obstacle.y}`"
           :style="obstacleStyle(obstacle)"></div>
           
      <!-- 豆豆 -->
      <div class="bean" 
           v-for="bean in beans" 
           :key="`bean-${bean.id}`"
           :style="beanStyle(bean)"
           :class="bean.type"></div>
    </div>

    <div class="start-screen" v-if="!gameActive && !gameOver">
      <h1>双人隐身追逐</h1>
      <button @click="startGame">开始游戏</button>
      <div class="instructions">
        <h3>游戏规则：</h3>
        <p>▶ 逃生者使用 WASD 移动（蓝色）</p>
        <p>▶ 追击者使用 方向键 移动（红色）</p>
        <p>▶ 双方速度相同</p>
        <p>▶ 草丛中双方完全隐身</p>
        <p>▶ 草丛在被玩家进入后6秒会消失</p>
        <p>▶ 游戏最后10秒所有草丛会消失</p>
        <p>▶ 逃生者到达逃生区域获胜</p>
        <p>▶ 追击者捕获逃生者获胜</p>
        <p>▶ 黄色豆豆：加速效果</p>
        <p>▶ 紫色豆豆：减速效果</p>
        <p>▶ 粉色豆豆：增大体积效果（300%）</p>
      </div>
    </div>

    <div class="game-over" v-if="gameOver">
      <h2 :class="gameResultClass">{{ gameResult }}</h2>
      <p>游戏时间：{{ formatTime(elapsedTime) }}</p>
      <button @click="startGame">再玩一次</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DualChaseGame',
  data() {
    return {
      // 玩家位置和状态
      escapePosition: { x: 300, y: 300 },
      chaserPosition: { x: 500, y: 300 },
      escapeSize: 20,
      chaserSize: 20,
      escapeSpeedMultiplier: 1,
      chaserSpeedMultiplier: 1,
      
      // 控制状态
      escapeControls: { up: false, down: false, left: false, right: false },
      chaserControls: { up: false, down: false, left: false, right: false },
      
      // 游戏状态
      gameActive: false,
      gameOver: false,
      gameResult: '',
      gameResultClass: '',
      elapsedTime: 0,
      escapeTimeNeeded: 60, // 需要存活60秒
      escapeTimeLeft: 0,
      
      // 游戏元素
      obstacles: [],
      bushes: [],
      beans: [],
      showEscapeZone: false,
      escapeZone: { x: 0, y: 0, size: 80 },
      
      // 速度设置
      baseSpeed: 4,
      
      // 草丛状态
      isEscapeInBush: false,
      isChaserInBush: false,
      currentBushIndex: -1,
      bushWarning: '',
      
      // 动画状态
      isDisappearing: false,
      
      // 计时器
      gameLoopId: null,
      gameTimer: null,
      beanTimer: null,
      bushTimers: {},
      effectTimers: {}
    };
  },
  computed: {
    escapeStyle() {
      return {
        left: `${this.escapePosition.x}px`,
        top: `${this.escapePosition.y}px`,
        width: `${this.escapeSize}px`,
        height: `${this.escapeSize}px`
      };
    },
    chaserStyle() {
      return {
        left: `${this.chaserPosition.x}px`,
        top: `${this.chaserPosition.y}px`,
        width: `${this.chaserSize}px`,
        height: `${this.chaserSize}px`
      };
    },
    escapeZoneStyle() {
      return {
        left: `${this.escapeZone.x - this.escapeZone.size/2}px`,
        top: `${this.escapeZone.y - this.escapeZone.size/2}px`,
        width: `${this.escapeZone.size}px`,
        height: `${this.escapeZone.size}px`
      };
    },
    // 计算属性：返回活跃的草丛
    activeBushes() {
      return this.bushes.filter(bush => bush.active);
    }
  },
  methods: {
    startGame() {
      this.gameActive = true;
      this.gameOver = false;
      this.elapsedTime = 0;
      this.escapeTimeLeft = this.escapeTimeNeeded;
      this.isDisappearing = false;
      this.obstacles = [];
      this.bushes = [];
      this.beans = [];
      this.showEscapeZone = false;
      this.bushTimers = {};
      this.bushWarning = '';
      this.escapeSize = 20;
      this.chaserSize = 20;
      this.escapeSpeedMultiplier = 1;
      this.chaserSpeedMultiplier = 1;
      
      this.generateObstacles();
      this.generateBushes();
      this.generateEscapeZone();
      
      // 重置位置
      this.escapePosition = this.getValidPosition(30);
      this.chaserPosition = this.getValidPosition(150);
      
      // 重置控制状态
      this.escapeControls = { up: false, down: false, left: false, right: false };
      this.chaserControls = { up: false, down: false, left: false, right: false };
      
      // 开始计时
      this.gameTimer = setInterval(() => {
        this.elapsedTime++;
        this.escapeTimeLeft = Math.max(0, this.escapeTimeNeeded - this.elapsedTime);
        
        // 30秒后显示逃生区域
        if (this.elapsedTime === 30) {
          this.showEscapeZone = true;
        }
        
        // 游戏最后10秒移除所有草丛
        if (this.escapeTimeLeft === 10) {
          this.bushWarning = '最后10秒！所有草丛将消失！';
          setTimeout(() => {
            this.bushes.forEach(bush => {
              bush.active = false;
            });
            this.bushWarning = '所有草丛已消失！';
            setTimeout(() => {
              this.bushWarning = '';
            }, 2000);
          }, 1000);
        }
        
        // 逃生者胜利条件1：存活足够时间
        if (this.elapsedTime >= this.escapeTimeNeeded) {
          this.endGame('追击者获胜！', 'chaser-win'); // 倒计时结束后改为追击者获胜
        }
      }, 1000);
      
      // 每10秒生成豆豆
      this.beanTimer = setInterval(this.generateBeans, 10000);
      
      this.gameLoop();
    },
    generateObstacles() {
      for (let i = 0; i < 10; i++) {
        this.obstacles.push({
          x: Math.random() * (window.innerWidth - 120),
          y: Math.random() * (window.innerHeight - 120),
          width: 80 + Math.random() * 80,
          height: 80 + Math.random() * 80
        });
      }
    },
    generateBushes() {
      for (let i = 0; i < 8; i++) {
        this.bushes.push({
          x: Math.random() * (window.innerWidth - 150),
          y: Math.random() * (window.innerHeight - 150),
          width: 120 + Math.random() * 80,
          height: 120 + Math.random() * 80,
          active: true
        });
      }
    },
    generateEscapeZone() {
      this.escapeZone = {
        x: Math.random() * (window.innerWidth - 200) + 100,
        y: Math.random() * (window.innerHeight - 200) + 100,
        size: 80
      };
    },
    generateBeans() {
      const beanTypes = ['speed', 'slow', 'grow'];
      const beanColors = {
        speed: { color: 'yellow', effect: 'speed' },
        slow: { color: 'purple', effect: 'slow' },
        grow: { color: 'pink', effect: 'grow' }
      };
      
      for (let i = 0; i < 5; i++) {
        const type = beanTypes[Math.floor(Math.random() * beanTypes.length)];
        const bean = {
          id: Date.now() + i,
          x: Math.random() * (window.innerWidth - 40) + 20,
          y: Math.random() * (window.innerHeight - 40) + 20,
          type: type,
          color: beanColors[type].color,
          effect: beanColors[type].effect,
          size: 15
        };
        
        this.beans.push(bean);
      }
    },
    getValidPosition(minDistance) {
      let pos, isValid;
      do {
        pos = {
          x: Math.random() * (window.innerWidth - 50) + 25,
          y: Math.random() * (window.innerHeight - 50) + 25
        };
        isValid = !this.checkCollision(pos.x, pos.y, minDistance);
      } while (!isValid);
      return pos;
    },
    // 键盘控制
    handleKeyDown(event) {
      // 逃生者控制 (WASD)
      switch(event.key.toLowerCase()) {
        case 'w': this.escapeControls.up = true; break;
        case 's': this.escapeControls.down = true; break;
        case 'a': this.escapeControls.left = true; break;
        case 'd': this.escapeControls.right = true; break;
      }
      
      // 追击者控制 (方向键)
      switch(event.key) {
        case 'ArrowUp': this.chaserControls.up = true; break;
        case 'ArrowDown': this.chaserControls.down = true; break;
        case 'ArrowLeft': this.chaserControls.left = true; break;
        case 'ArrowRight': this.chaserControls.right = true; break;
      }
    },
    handleKeyUp(event) {
      // 逃生者控制 (WASD)
      switch(event.key.toLowerCase()) {
        case 'w': this.escapeControls.up = false; break;
        case 's': this.escapeControls.down = false; break;
        case 'a': this.escapeControls.left = false; break;
        case 'd': this.escapeControls.right = false; break;
      }
      
      // 追击者控制 (方向键)
      switch(event.key) {
        case 'ArrowUp': this.chaserControls.up = false; break;
        case 'ArrowDown': this.chaserControls.down = false; break;
        case 'ArrowLeft': this.chaserControls.left = false; break;
        case 'ArrowRight': this.chaserControls.right = false; break;
      }
    },
    gameLoop() {
      if (!this.gameActive) return;
      
      this.moveEscape();
      this.moveChaser();
      this.checkBushStatus();
      this.checkCollisionDetection();
      this.checkEscapeZone();
      this.checkBeanCollection();
      
      this.gameLoopId = requestAnimationFrame(this.gameLoop);
    },
    checkBushStatus() {
      this.isEscapeInBush = this.checkInBush(this.escapePosition.x, this.escapePosition.y);
      this.isChaserInBush = this.checkInBush(this.chaserPosition.x, this.chaserPosition.y);
      
      // 检查逃生者是否在草丛中
      if (this.isEscapeInBush) {
        const bushIndex = this.getBushIndex(this.escapePosition.x, this.escapePosition.y);
        if (bushIndex !== -1 && this.bushes[bushIndex].active) {
          if (this.currentBushIndex !== bushIndex) {
            // 进入新草丛，重置计时器
            this.currentBushIndex = bushIndex;
            if (this.bushTimers[bushIndex]) {
              clearTimeout(this.bushTimers[bushIndex]);
            }
            
            this.bushTimers[bushIndex] = setTimeout(() => {
              if (this.bushes[bushIndex] && this.bushes[bushIndex].active) {
                this.bushes[bushIndex].active = false;
                this.bushWarning = `草丛已消失！`;
                setTimeout(() => {
                  this.bushWarning = '';
                }, 2000);
              }
            }, 6000);
          }
        }
      } else {
        // 逃生者离开草丛
        this.currentBushIndex = -1;
      }
    },
    getBushIndex(x, y) {
      for (let i = 0; i < this.bushes.length; i++) {
        const bush = this.bushes[i];
        if (!bush.active) continue; // 跳过已消失的草丛
        
        if (x > bush.x && 
            x < bush.x + bush.width &&
            y > bush.y && 
            y < bush.y + bush.height) {
          return i;
        }
      }
      return -1;
    },
    checkInBush(x, y) {
      return this.bushes.some((bush) => {
        if (!bush.active) return false;
        return x > bush.x && 
               x < bush.x + bush.width &&
               y > bush.y && 
               y < bush.y + bush.height;
      });
    },
    moveEscape() {
      if (this.isDisappearing) return;
      
      let newX = this.escapePosition.x;
      let newY = this.escapePosition.y;

      if (this.escapeControls.up) newY -= this.baseSpeed * this.escapeSpeedMultiplier;
      if (this.escapeControls.down) newY += this.baseSpeed * this.escapeSpeedMultiplier;
      if (this.escapeControls.left) newX -= this.baseSpeed * this.escapeSpeedMultiplier;
      if (this.escapeControls.right) newX += this.baseSpeed * this.escapeSpeedMultiplier;

      // 边界限制
      newX = Math.max(30, Math.min(window.innerWidth - 30, newX));
      newY = Math.max(30, Math.min(window.innerHeight - 30, newY));

      if (!this.checkCollision(newX, newY, 15)) {
        this.escapePosition.x = newX;
        this.escapePosition.y = newY;
      }
    },
    moveChaser() {
      let newX = this.chaserPosition.x;
      let newY = this.chaserPosition.y;

      if (this.chaserControls.up) newY -= this.baseSpeed * this.chaserSpeedMultiplier;
      if (this.chaserControls.down) newY += this.baseSpeed * this.chaserSpeedMultiplier;
      if (this.chaserControls.left) newX -= this.baseSpeed * this.chaserSpeedMultiplier;
      if (this.chaserControls.right) newX += this.baseSpeed * this.chaserSpeedMultiplier;

      // 边界限制
      newX = Math.max(30, Math.min(window.innerWidth - 30, newX));
      newY = Math.max(30, Math.min(window.innerHeight - 30, newY));

      if (!this.checkCollision(newX, newY, 15)) {
        this.chaserPosition.x = newX;
        this.chaserPosition.y = newY;
      }
    },
    checkCollision(x, y, radius) {
      if (x < radius || x > window.innerWidth - radius || 
          y < radius || y > window.innerHeight - radius) {
        return true;
      }

      return this.obstacles.some(obs => {
        return x + radius > obs.x &&
               x - radius < obs.x + obs.width &&
               y + radius > obs.y &&
               y - radius < obs.y + obs.height;
      });
    },
    checkCollisionDetection() {
      // 双方都在草丛中时不检测碰撞
      if (this.isEscapeInBush && this.isChaserInBush) return;
      if (this.isDisappearing) return;
      
      const dx = this.escapePosition.x - this.chaserPosition.x;
      const dy = this.escapePosition.y - this.chaserPosition.y;
      const distance = Math.sqrt(dx * dx + dy * dy);

      if (distance < 25) {
        this.escapeCaught();
      }
    },
    checkEscapeZone() {
      if (!this.showEscapeZone || this.isDisappearing) return;
      
      const dx = this.escapePosition.x - this.escapeZone.x;
      const dy = this.escapePosition.y - this.escapeZone.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance < this.escapeZone.size/2) {
        this.endGame('逃生者获胜！', 'escape-win');
      }
    },
    checkBeanCollection() {
      // 检查逃生者是否收集豆豆
      for (let i = this.beans.length - 1; i >= 0; i--) {
        const bean = this.beans[i];
        const dx = this.escapePosition.x - bean.x;
        const dy = this.escapePosition.y - bean.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < this.escapeSize/2 + bean.size/2) {
          this.applyBeanEffect('escape', bean);
          this.beans.splice(i, 1);
        }
      }
      
      // 检查追击者是否收集豆豆
      for (let i = this.beans.length - 1; i >= 0; i--) {
        const bean = this.beans[i];
        const dx = this.chaserPosition.x - bean.x;
        const dy = this.chaserPosition.y - bean.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < this.chaserSize/2 + bean.size/2) {
          this.applyBeanEffect('chaser', bean);
          this.beans.splice(i, 1);
        }
      }
    },
    applyBeanEffect(player, bean) {
      if (bean.effect === 'speed') {
        if (player === 'escape') {
          this.escapeSpeedMultiplier = 1.5;
          this.effectTimers.escapeSpeed = setTimeout(() => {
            this.escapeSpeedMultiplier = 1;
          }, 5000);
        } else {
          this.chaserSpeedMultiplier = 1.5;
          this.effectTimers.chaserSpeed = setTimeout(() => {
            this.chaserSpeedMultiplier = 1;
          }, 5000);
        }
      } else if (bean.effect === 'slow') {
        if (player === 'escape') {
          this.escapeSpeedMultiplier = 0.5;
          this.effectTimers.escapeSlow = setTimeout(() => {
            this.escapeSpeedMultiplier = 1;
          }, 5000);
        } else {
          this.chaserSpeedMultiplier = 0.5;
          this.effectTimers.chaserSlow = setTimeout(() => {
            this.chaserSpeedMultiplier = 1;
          }, 5000);
        }
      } else if (bean.effect === 'grow') {
        if (player === 'escape') {
          this.escapeSize = 60; // 增加至300%
          this.effectTimers.escapeGrow = setTimeout(() => {
            this.escapeSize = 20;
          }, 5000);
        } else {
          this.chaserSize = 60; // 增加至300%
          this.effectTimers.chaserGrow = setTimeout(() => {
            this.chaserSize = 20;
          }, 5000);
        }
      }
    },
    escapeCaught() {
      this.isDisappearing = true;
      setTimeout(() => {
        this.endGame('追击者获胜！', 'chaser-win');
      }, 1000); // 消散动画持续时间
    },
    endGame(result, resultClass) {
      this.gameResult = result;
      this.gameResultClass = resultClass;
      cancelAnimationFrame(this.gameLoopId);
      clearInterval(this.gameTimer);
      clearInterval(this.beanTimer);
      this.gameActive = false;
      this.gameOver = true;
    },
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins}:${secs.toString().padStart(2, '0')}`;
    },
    obstacleStyle(obstacle) {
      return {
        left: `${obstacle.x}px`,
        top: `${obstacle.y}px`,
        width: `${obstacle.width}px`,
        height: `${obstacle.height}px`,
        borderRadius: `${obstacle.width / 8}px`
      };
    },
    bushStyle(bush) {
      return {
        left: `${bush.x}px`,
        top: `${bush.y}px`,
        width: `${bush.width}px`,
        height: `${bush.height}px`,
        borderRadius: `${bush.width / 4}px`
      };
    },
    beanStyle(bean) {
      return {
        left: `${bean.x}px`,
        top: `${bean.y}px`,
        width: `${bean.size}px`,
        height: `${bean.size}px`,
        backgroundColor: bean.color,
        borderRadius: '50%'
      };
    }
  },
  mounted() {
    window.addEventListener('keydown', this.handleKeyDown);
    window.addEventListener('keyup', this.handleKeyUp);
  },
  beforeDestroy() {
    window.removeEventListener('keydown', this.handleKeyDown);
    window.removeEventListener('keyup', this.handleKeyUp);
    cancelAnimationFrame(this.gameLoopId);
    clearInterval(this.gameTimer);
    clearInterval(this.beanTimer);
  }
};
</script>

<style scoped>
.background {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  overflow: hidden;
}

#game-container {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.status-bar {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  color: white;
  font-family: 'Arial Black', sans-serif;
  background: rgba(0, 0, 0, 0.7);
  padding: 10px 25px;
  border-radius: 15px;
  z-index: 100;
}

.controls {
  display: flex;
  gap: 20px;
  margin-top: 5px;
  font-size: 14px;
}

.escape-time {
  margin-top: 5px;
  color: #00ffff;
  font-weight: bold;
}

.bush-warning {
  margin-top: 5px;
  color: #ff9900;
  font-weight: bold;
  animation: pulse 1s infinite;
}

.player {
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: all 0.1s ease-out;
  z-index: 10;
}

.escape {
  background: radial-gradient(circle at 30% 30%, #00ffff, #0066ff);
  box-shadow: 0 0 15px rgba(0, 255, 255, 0.7);
}

.escape.disappearing {
  animation: dissolve 1s forwards;
}

.dissolve-effect {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(0,255,255,0.8) 0%, rgba(0,255,255,0) 70%);
  animation: pulse 0.5s infinite alternate;
}

.chaser {
  background: radial-gradient(circle at 30% 30%, #ff4444, #cc0000);
  box-shadow: 0 0 15px rgba(255, 68, 68, 0.7);
}

.hidden {
  opacity: 0;
}

.obstacle {
  position: absolute;
  background: linear-gradient(45deg, #2c3e50, #34495e);
  box-shadow: 0 0 20px rgba(44, 62, 80, 0.6);
  border: 2px solid #3b4d5e;
  z-index: 5;
}

.bush {
  position: absolute;
  background: rgba(50, 205, 50, 0.2);
  box-shadow: 0 0 25px rgba(50, 205, 50, 0.3);
  border: 1px solid rgba(34, 139, 34, 0.3);
  z-index: 2;
}

.escape-zone {
  position: absolute;
  border-radius: 50%;
  background: rgba(0, 255, 255, 0.1);
  border: 2px dashed rgba(0, 255, 255, 0.5);
  z-index: 3;
  animation: pulse 2s infinite;
}

.bean {
  position: absolute;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  z-index: 5;
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
}

.bean.speed {
  box-shadow: 0 0 15px yellow;
}

.bean.slow {
  box-shadow: 0 0 15px purple;
}

.bean.grow {
  box-shadow: 0 0 15px pink;
}

.start-screen, .game-over {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
  background: rgba(0, 0, 0, 0.85);
  padding: 30px 50px;
  border-radius: 25px;
  border: 2px solid #00ffff;
  backdrop-filter: blur(8px);
  box-shadow: 0 0 30px rgba(0, 255, 255, 0.3);
  z-index: 200;
}

button {
  background: linear-gradient(45deg, #00b4d8, #0096c7);
  color: white;
  border: none;
  padding: 12px 35px;
  font-size: 16px;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 15px 0;
  font-weight: bold;
}

button:hover {
  transform: scale(1.1);
  box-shadow: 0 0 20px #00b4d8;
}

.game-over h2 {
  margin-bottom: 20px;
}

.escape-win {
  color: #00ffff;
  text-shadow: 0 0 10px rgba(0, 255, 255, 0.7);
}

.chaser-win {
  color: #ff4444;
  text-shadow: 0 0 10px rgba(255, 68, 68, 0.7);
}

@keyframes dissolve {
  0% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
  100% { transform: translate(-50%, -50%) scale(3); opacity: 0; }
}

@keyframes pulse {
  0% { opacity: 0.6; }
  100% { opacity: 1; }
}
</style>